package com.nwpu.vote.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nwpu.vote.model.*;
import com.nwpu.vote.util.*;
import com.nwpu.vote.control.*;
import com.nwpu.vote.parser.*;

public class VoteCreateServlet extends HttpServlet {
	
	private static java.util.logging.Logger logger = Logger.getLogger(VoteCreateServlet.class.getName());
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			Vote vote = new VoteParser().parse(req);
			
			//save the vote to Google data store
			VotePersistentImpl.instance.save(vote);
			
			//TODO lucene index
			//LuceneIndexer.instance.doIndex(file);
			
			resp.setStatus(200);
			req.getRequestDispatcher("/newvotesuccess.html").forward(req, resp);
			resp.setContentType("text/plain;charset=utf-8");
			PrintWriter pw = resp.getWriter();
			pw.write("the vote is created successfully");
			
		} catch (InvalidNewVoteException e) {
			resp.setStatus(200);
			PrintWriter pw = resp.getWriter();
			pw.write("Exception:"+e.getMessage());
			e.printStackTrace(pw);
			
			logger.log(Level.FINE, e.getMessage(),e);
		} catch (PersistentException e) {
			resp.setStatus(200);
			PrintWriter pw = resp.getWriter();
			pw.write("Exception:"+e.getMessage());
			e.printStackTrace(pw);
			
			logger.log(Level.FINE, e.getMessage(),e);
		}
		/*catch (IndexFailedException e) {
			resp.setStatus(200);
			PrintWriter pw = resp.getWriter();
			pw.write("Exception:"+e.getMessage());
			e.printStackTrace(pw);
			
			logger.log(Level.WARNING, e.getMessage(),e);
		}*/
		
	}
}
